package com.bolingcavalry.crm.serviceproblem.service.impl;/*
 * @Auther:Sadie
 * @Date:2025/5/19
 * @Description:
 * @VERSON:1.8
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.ResponseResult;
import com.base.Status;
import com.bolingcavalry.crm.aftersales.mapper.AfterSalesMapper;
import com.bolingcavalry.crm.customer.mapper.CustomerCompaniesMapper;
import com.bolingcavalry.crm.message.config.RabbitMQConstants;
import com.bolingcavalry.crm.product.mapper.ProductMapper;
import com.bolingcavalry.crm.security.utils.SecurityUtils;
import com.bolingcavalry.crm.serviceproblem.service.ServiceProblemService;
import com.bolingcavalry.crm.serviceproblem.mapper.ServiveProblemMapper;
import com.bolingcavalry.crm.taskorder.mapper.TaskorderMapper;
import com.bolingcavalry.crm.utils.AUtils;
import com.dto.serviceproblem.ServiceProblemDTO;
import com.dto.TaskReviewMessageDTO;
import com.entity.aftersales.AfterSales;
import com.entity.product.Product;
import com.entity.serviceproblem.ServiceProblem;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vo.ServiceProblemCountVO;
import com.vo.ServiceProblemStatusCountVO;
import com.vo.ServiceProblemVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class ServiceProblemServiceImpl implements ServiceProblemService {
    @Autowired
    private ServiveProblemMapper serviceProblemMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private TaskorderMapper taskorderMapper;
    @Autowired
    private AUtils aUtils;
    @Autowired
    private AfterSalesMapper afterSalesMapper;
    @Autowired
    private CustomerCompaniesMapper customerCompanyMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    // 添加 ObjectMapper 注入
    @Autowired
    private ObjectMapper objectMapper;


    /**
     * 添加服务问题信息
     * @param serviceProblemDTO
     */
    @Override
    public ResponseResult add(ServiceProblemDTO serviceProblemDTO) {

        if(StringUtils.isBlank(serviceProblemDTO.getProductName()))
            return ResponseResult.error("请检查产品名称填写");
        if(serviceProblemDTO.getFaultDescription()==null||serviceProblemDTO.getFaultDescription().isEmpty())
            return ResponseResult.error("请检查故障现象填写");
        if(serviceProblemDTO.getFaultAnalysis()==null||serviceProblemDTO.getFaultAnalysis().isEmpty())
            return ResponseResult.error("请检查故障分析填写");
        if(serviceProblemDTO.getResolutionMethod()==null||serviceProblemDTO.getResolutionMethod().isEmpty())
            return ResponseResult.error("请检查排除方法填写");
        if(serviceProblemDTO.getResolutionResult()==null||serviceProblemDTO.getResolutionResult().isEmpty())
            return ResponseResult.error("请检查处理结果填写");


        if(!serviceProblemDTO.getResolutionDate().isEmpty()&&serviceProblemDTO.getResolutionDate().length()>=10){
            //只取年月日
            serviceProblemDTO.setResolutionDate(serviceProblemDTO.getResolutionDate().substring(0,10));
        }
        else serviceProblemDTO.setResolutionDate(null);
        //怎么加入产品呢（只存储产品的名称）
        ServiceProblem serviceProblem = new ServiceProblem();
        BeanUtils.copyProperties(serviceProblemDTO, serviceProblem);
        if (serviceProblemDTO.getResolutionDate()!=null)
        serviceProblem.setResolutionDate(LocalDate.parse(serviceProblemDTO.getResolutionDate()));
        //设置创建人
        serviceProblem.setCreatedBy(aUtils.getNickNameByuserName(SecurityUtils.getCurrentUsername()));
        serviceProblem.setCreateTime(LocalDateTime.now());
        try {
            serviceProblemMapper.insert(serviceProblem);
            //创建消息通知全体人员？
//            TaskReviewMessageDTO taskReviewMessageDTO = new TaskReviewMessageDTO();
//            //设置当前服务单编号
//            taskReviewMessageDTO.setOrderNumber(aUtils.getAfterSalesNumberById(serviceProblemDTO.getAfterSalesId()));
//            taskReviewMessageDTO.setServiceProblemId(serviceProblem.getId());
//            taskReviewMessageDTO.setTitle("服务问题创建通知");
//
//            // 修改后 - 方式3：使用Optional（Java 8+）
//            taskReviewMessageDTO.setContent(
//                    "创建人:"+aUtils.getNickNameByuserName(SecurityUtils.getCurrentUsername()) +"\n"+"服务问题:"+
//                    Optional.ofNullable(serviceProblemDTO.getProductName()).orElse("") +
//                    Optional.ofNullable(serviceProblemDTO.getFaultDescription()).orElse("") +
//                            "的服务问题"
//            );
//            taskReviewMessageDTO.setSenderName(aUtils.getNickNameByuserName(SecurityUtils.getCurrentUsername()));
//            taskReviewMessageDTO.setBusinessType(Status.SERVICE_PROBLEM);
//
//            //创建一个全体成员的消息
//            //taskReviewMessageDTO.setRoleName(RoleEnum.GENERAL_COMMAND.getCode());
//            rabbitTemplate.convertAndSend(
//                    RabbitMQConstants.EXCHANGE,
//                    RabbitMQConstants.ROUTING_KEY_SERVICE_PROBLEM,
//                    taskReviewMessageDTO
//            );
        } catch (Exception e) {
            return ResponseResult.error("新增失败");
        }
        return ResponseResult.success("新增成功",serviceProblem.getId());
    }

    /**
     * 更新服务问题信息
     * @param serviceProblemDTO
     */
    @Override
    public ResponseResult update(ServiceProblemDTO serviceProblemDTO) {
        // 1. 检查ID是否存在
        ServiceProblem existing = serviceProblemMapper.selectById(serviceProblemDTO.getId());
        if (existing == null) {
            throw new RuntimeException("未找到ID为 " + serviceProblemDTO.getId() + " 的服务");
        }
        //根据传入的serviceProblemDTO的afterid查询对应的售后单id
        //首先判断是否afterid长度是否大于等于20000000
        if(serviceProblemDTO.getAfterSalesId()>=20000000){
            serviceProblemDTO.setAfterSalesId(aUtils.getAfterSalesIdByNumber(serviceProblemDTO.getAfterSalesId()));
        }

        // 2. 转换 DTO -> Entity
        ServiceProblem serviceProblem = new ServiceProblem();
        BeanUtils.copyProperties(serviceProblemDTO,serviceProblem);
        if(!serviceProblemDTO.getResolutionDate().isEmpty()&&serviceProblemDTO.getResolutionDate().length()>=10){
            //只取年月日
            serviceProblemDTO.setResolutionDate(serviceProblemDTO.getResolutionDate().substring(0,10));
        }
        else serviceProblemDTO.setResolutionDate(null);
        if (serviceProblemDTO.getResolutionDate()!=null)
            serviceProblem.setResolutionDate(LocalDate.parse(serviceProblemDTO.getResolutionDate()));
        serviceProblem.setUpdateTime(LocalDateTime.now());
        // 3. 更新数据
        try {
            serviceProblemMapper.updateById(serviceProblem);
        } catch (Exception e) {
            return ResponseResult.error("更新失败");
        }
        return ResponseResult.success("更新成功");
    }

    /**
     * 修改状态
     * @param id
     * @param status
     * @return
     */
    @Override
    public Boolean updateStatus(Long id, Integer status) {
        // 1. 参数校验
        if (id == null || status == null) {
            log.warn("参数错误：id 或 status 为空");
            return false;
        }
        // 2. 查询原数据是否存在
        ServiceProblem problem = serviceProblemMapper.selectById(id);
        if (problem == null) {
            log.warn("未找到 ID 为 {} 的服务问题", id);
            return false;
        }
        // 3. 将数字状态转换为对应的状态字符串
        String targetStatus;
        switch (status) {
            case 1:
                //编辑中
                targetStatus = Status.SERVICE_ORDER_STATUS_EDITING; // "editing"
                break;
            case 2:
                //已确认
                targetStatus = Status.SERVICE_ORDER_STATUS_CONFIRMED; // "confirmed"
                break;
            case 3:
                //已发布
                targetStatus = Status.SERVICE_ORDER_STATUS_PUBLISHED; // "published"
                break;
            case 4:
                //已完成
                targetStatus = Status.SERVICE_ORDER_STATUS_COMPLETED; // "completed"
                break;
            case 5:
                //处理中
                targetStatus = Status.SERVICE_ORDER_STATUS_PROCESSING; // "processing"
                break;
            case 6:
                //已归档
                targetStatus = Status.SERVICE_ORDER_STATUS_ARCHIVED; // "archived"
                break;
            default:
                log.warn("无效的状态码: {}", status);
                return false;
        }
        // 4. 设置新状态并更新
        problem.setStatus(targetStatus);
        try {
            int result = serviceProblemMapper.updateById(problem);
            if (result!=1) {
                log.warn("更新失败，可能是数据未更改或并发冲突，ID: {}", id);
            }
            return true;
        } catch (Exception e) {
            log.error("更新服务问题状态时发生异常，ID: {}", id, e);
            return false;
        }
    }

    /**
     * 批量逻辑删除
     * @param ids
     * @return
     */
    @Override
    public List<Long>  batchDelete(Long[] ids) {
        List<Long> failedIds = new ArrayList<>();
        if (ids == null || ids.length == 0) {
            log.warn("传入的 ID 数组为空");
            return failedIds; // 返回空列表表示没有操作
        }
        for (Long id : ids) {
            try {
                // 构建更新对象
                ServiceProblem serviceProblem = serviceProblemMapper.selectById(id);
                if (serviceProblem == null) {
                    log.warn("ID 为 {} 的记录不存在", id);
                    failedIds.add(id);
                    continue;
                }
                serviceProblem.setIsDeleted(0); // 标记为已删除
                serviceProblemMapper.updateById(serviceProblem);


            } catch (Exception e) {
                log.error("批量逻辑删除失败", e);
                failedIds.add(id);
            }
        }
        return failedIds;
    }

    /**
     * 根据id查询服务问题详细
     * @param id
     * @return
     */
    @Override
    public ServiceProblemVO getById(Long id) {
        // 1. 查询服务问题实体
        ServiceProblem serviceProblem = serviceProblemMapper.selectById(id);
        String photos = serviceProblemMapper.getPhotos(id);
        ServiceProblemVO serviceProblemVO = new ServiceProblemVO();
        // 2. DTO → VO 转换
        BeanUtils.copyProperties(serviceProblem, serviceProblemVO);
        try {
            if (photos != null && !photos.isEmpty() && !photos.equals("[]")) {
                // 解析 JSON 数组字符串为 List<String>
                List<String> photosList = objectMapper.readValue(photos, new TypeReference<List<String>>() {});
                serviceProblemVO.setPhotos(photosList); // 假设 VO 中的 setPhotos 接收 List<String>
            } else {
                // 如果没有图片数据，设置为空列表
                serviceProblemVO.setPhotos(new ArrayList<>());
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        if (serviceProblem.getIsDeleted() != 0) {
            if (serviceProblem == null) {
                throw new RuntimeException("未找到ID为 " + id + " 的服务问题");
            }

            // 3. 查询产品名称
            if(serviceProblem.getProductId()!=null){
                Product product = productMapper.selectById(serviceProblem.getProductId());
                serviceProblemVO.setProductName(product != null ? product.getName() : null);
            }
            // 4. 查询售后单号
            if(serviceProblem.getAfterSalesId()!=null){
                AfterSales afterSales = afterSalesMapper.selectById(serviceProblem.getAfterSalesId());
                serviceProblemVO.setAfterSalesId(afterSales != null ? afterSales.getOrderNumber() : null);
            }
            // 5. 查询客户公司名称
            if(serviceProblem.getCustomerCompanyId()!=null){
                serviceProblemVO.setCustomerCompanyName(aUtils.getCustomerCompanyNameById(serviceProblem.getCustomerCompanyId()));
            }
            return serviceProblemVO;
        }
        return null;

    }

    /**
     * 分页条件查询服务问题
     * @return
     */
    @Override
    public IPage<ServiceProblemVO> list(Integer pageNum,
                                        Integer pageSize,
                                        String OrderNumber,
                                        String installStation,
                                        String installationLocation,
                                        String boreSize,
                                        String modelNumber,
                                        String productionNumber,
                                        String problemCategory,
                                        String startDate,
                                        String endDate,
                                        Integer status,
                                        String customerCompanyName,
                                        String faultDescription,
                                        String keyword,
                                        String createdBy) {
        LambdaQueryWrapper<ServiceProblem> queryWrapper = new LambdaQueryWrapper<>();
        //keyword（客户名称、安装站名、位置、售后单号、出厂编号模糊匹配）
        if(keyword!=null){
            // 客户名称模糊匹配
            List<Long> companyIds = customerCompanyMapper.selectCompanyIdsByName(keyword);
            if (companyIds != null && !companyIds.isEmpty()) {
                queryWrapper.in(ServiceProblem::getCustomerCompanyId, companyIds);
            }

            // 售后单号模糊匹配
            List<Long> afterSalesIds = afterSalesMapper.selectIdsByOrderNumber(keyword);
            if (afterSalesIds != null && !afterSalesIds.isEmpty()) {
                queryWrapper.in(ServiceProblem::getAfterSalesId, afterSalesIds);
            }
            //客户名称模糊匹配
            queryWrapper.like(ServiceProblem::getInstallStation, keyword)
                    .or()
                    .like(ServiceProblem::getInstallationLocation, keyword);
            //出厂编号模糊匹配
            queryWrapper.like(ServiceProblem::getProductionNumber, keyword);
        }
        if(createdBy!=null){
            createdBy=aUtils.getNickNameByuserName(SecurityUtils.getCurrentUsername());
            queryWrapper.eq(ServiceProblem::getCreatedBy, createdBy);
        }
        //根据售后单号模糊匹配
        if (StringUtils.isNotBlank(OrderNumber)) {
            //因为和售后是关联的所以在数据库层面模糊匹配
            List<Long> afterSalesId = afterSalesMapper.selectIdsByOrderNumber(OrderNumber);
            if (afterSalesId != null && !afterSalesId.isEmpty()) {
                queryWrapper.in(ServiceProblem::getAfterSalesId, afterSalesId);
            }
            else {
                // 如果没有匹配的 afterSalesId，则强制查询一个永远不存在的值
                queryWrapper.eq(ServiceProblem::getAfterSalesId, -1L);
            }
        }
        //安装站名
        if(installStation!=null){
            queryWrapper.like(ServiceProblem::getInstallStation, installStation);
        }
        //位置
        if(installationLocation!=null){
            queryWrapper.like(ServiceProblem::getInstallationLocation, installationLocation);
        }
        //口径
        if(boreSize!=null){
            queryWrapper.eq(ServiceProblem::getBoreSize, boreSize);
        }
        //型号
        if(modelNumber!=null){
            queryWrapper.eq(ServiceProblem::getModelNumber, modelNumber);
        }
        //产品生产编号
        if(productionNumber!=null){
            queryWrapper.like(ServiceProblem::getProductionNumber, productionNumber);
        }
        //问题类别
        if(problemCategory!=null){
            queryWrapper.eq(ServiceProblem::getProblemCategory, problemCategory);
        }
        //根据开始和结束时间查询
        if (StringUtils.isNotBlank(startDate)) {
            queryWrapper.ge(ServiceProblem::getCreateTime, startDate);
        }
        if (StringUtils.isNotBlank(endDate)) {
            queryWrapper.le(ServiceProblem::getCreateTime, endDate);
        }
        if(status!=null){
            queryWrapper.eq(ServiceProblem::getStatus, status);
        }
        //处理故障现象
        if (StringUtils.isNotBlank(faultDescription)) {
            queryWrapper.eq(ServiceProblem::getFaultDescription, faultDescription);
        }
        // 处理客户公司名称模糊查询
        if (StringUtils.isNotBlank(customerCompanyName)) {
            // 调用客户公司 Mapper 模糊查询公司ID列表
            List<Long> companyIds = customerCompanyMapper.selectCompanyIdsByName(customerCompanyName);
            if (!companyIds.isEmpty()) {
                // 匹配所有模糊查询到的客户公司ID
                queryWrapper.in(ServiceProblem::getCustomerCompanyId, companyIds);
            }
        }
        queryWrapper.eq(ServiceProblem::getIsDeleted, 1);
        // 添加默认排序：按处理时间(resolutionDate)降序排列
        queryWrapper.orderByDesc(ServiceProblem::getResolutionDate);

        // 执行查询
        IPage<ServiceProblem> resultPage;
        if (pageSize == null) {
            // 查询全部数据
            IPage<ServiceProblem> page = new Page<>(1, 100000); // 使用足够大的页面大小
            resultPage = serviceProblemMapper.selectPage(page, queryWrapper);

            // 调整分页信息，使其更符合"查询全部"的语义
            resultPage.setPages(1);
            resultPage.setCurrent(1);
            resultPage.setSize(resultPage.getTotal());
        } else {
            // 正常分页查询
            IPage<ServiceProblem> page = new Page<>(pageNum, pageSize);
            resultPage = serviceProblemMapper.selectPage(page, queryWrapper);
        }

        // 转换为 VO 层对象
        return resultPage.convert(this::convertToVO);
    }



    /**
     * vo  转换
     * @param serviceProblem
     * @return
     */
    private ServiceProblemVO convertToVO(ServiceProblem serviceProblem) {
        ServiceProblemVO vo = new ServiceProblemVO();
        BeanUtils.copyProperties(serviceProblem, vo);
        //查询产品名称
        if(serviceProblem.getProductId()!=null){
            Product product = productMapper.selectById(serviceProblem.getProductId());
            vo.setProductName(product != null ? product.getName() : null);
        }
        //查询售后单号
        if(serviceProblem.getAfterSalesId()!=null){
            AfterSales afterSales = afterSalesMapper.selectById(serviceProblem.getAfterSalesId());
            vo.setAfterSalesId(afterSales != null ? afterSales.getOrderNumber() : null);
        }
        //查询公司名称
        if(serviceProblem.getCustomerCompanyId()!=null){
            vo.setCustomerCompanyName(aUtils.getCustomerCompanyNameById(serviceProblem.getCustomerCompanyId()));
            vo.setCustomerCompanyId(serviceProblem.getCustomerCompanyId());
        }

        // 处理图片数据 - 复用getById中的逻辑
        try {
            String photos = serviceProblemMapper.getPhotos(serviceProblem.getId());
            if (photos != null && !photos.isEmpty() && !photos.equals("[]")) {
                // 解析 JSON 数组字符串为 List<String>
                List<String> photosList = objectMapper.readValue(photos, new TypeReference<List<String>>() {});
                vo.setPhotos(photosList); // 假设 VO 中的 setPhotos 接收 List<String>
            } else {
                // 如果没有图片数据，设置为空列表
                vo.setPhotos(new ArrayList<>());
            }
        } catch (Exception e) {
            // 如果解析失败，设置为空列表
            vo.setPhotos(new ArrayList<>());
        }

        return vo;
    }


    @Override
    public ServiceProblemStatusCountVO getCount() {
        ServiceProblemStatusCountVO vo = new ServiceProblemStatusCountVO();
        vo.setTotal(serviceProblemMapper.countAll());
        vo.setMonthly(serviceProblemMapper.countMonthly());
        return vo;
    }

    @Override
    public List<ServiceProblemCountVO> problemCategoryCount() {
        return serviceProblemMapper.problemCategoryCount();
        //返回扁平的数据类型如何进行筛选呢？
    }

    @Override
    public ResponseResult<String> getCopyByIds(List<Long> ids) {
        // 1. 输入校验
        if (ids == null || ids.isEmpty()) {
            return ResponseResult.error("ID列表不能为空");
        }

        // 2. 用于存储按日期分组的最终结果
        // 使用 LinkedHashMap 保持日期插入顺序
        java.util.Map<String, StringBuilder> resultMap = new java.util.LinkedHashMap<>();

        // 3. 定义日期格式化器 (只取日期部分)
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 4. 遍历 ID 列表
        for (Long id : ids) {
            // 5. 根据 ID 获取 ServiceProblemVO 对象
            ServiceProblemVO problem = getById(id); // <-- 请确保此方法正确调用你的服务层方法

            // 6. 数据校验：检查问题是否存在
            if (problem == null) {
                return ResponseResult.error("未找到ID为 " + id + " 的服务问题");
            }

            // 7. 获取并格式化处理日期，作为分组键
            String resolutionDateStr;
            if (problem.getResolutionDate() != null) {
                resolutionDateStr = problem.getResolutionDate().format(dateFormatter);
            } else {
                resolutionDateStr = "未指定处理日期";
            }

            // 8. 获取或创建该日期对应的 StringBuilder
            StringBuilder dateContent = resultMap.computeIfAbsent(resolutionDateStr, k -> new StringBuilder());

            // 9. 拼接单个问题的内容
            // 计算当前日期下已有的问题条数，用于生成 "问题X：" 序号
            String currentContent = dateContent.toString();
            long problemCountForThisDate = currentContent.lines().filter(line -> line.startsWith("🔹 问题")).count() + 1;

            dateContent.append("🔹 问题").append(problemCountForThisDate).append("：\n");

            // --- 拼接具体字段 (包含所有 VO 字段，根据需要调整顺序和格式) ---

            // 售后单号
            if (problem.getAfterSalesId() != null && !problem.getAfterSalesId().isEmpty()) {
                dateContent.append("售后单号：").append(problem.getAfterSalesId()).append("\n");
            }
            // 客户公司名称
            if (problem.getCustomerCompanyName() != null && !problem.getCustomerCompanyName().isEmpty()) {
                dateContent.append("客户：").append(problem.getCustomerCompanyName()).append("\n");
            }

            // 产品信息 (产品名称 | 问题归类 | 口径 | 材质 | 型号)
            StringBuilder productInfoBuilder = new StringBuilder();
            if (problem.getProductName() != null && !problem.getProductName().isEmpty()) {
                productInfoBuilder.append(problem.getProductName());
            }
            if (problem.getProblemCategory() != null && !problem.getProblemCategory().isEmpty()) {
                if (productInfoBuilder.length() > 0) productInfoBuilder.append(" | ");
                productInfoBuilder.append("类型：").append(problem.getProblemCategory());
            }
            if (problem.getBoreSize() != null && !problem.getBoreSize().isEmpty()) {
                if (productInfoBuilder.length() > 0) productInfoBuilder.append(" | ");
                productInfoBuilder.append("口径：").append(problem.getBoreSize());
            }
            if (problem.getMaterial() != null && !problem.getMaterial().isEmpty()) {
                if (productInfoBuilder.length() > 0) productInfoBuilder.append(" | ");
                productInfoBuilder.append("材质：").append(problem.getMaterial());
            }
            if (problem.getModelNumber() != null && !problem.getModelNumber().isEmpty()) {
                if (productInfoBuilder.length() > 0) productInfoBuilder.append(" | ");
                productInfoBuilder.append("型号：").append(problem.getModelNumber());
            }
            if (productInfoBuilder.length() > 0) {
                dateContent.append("产品：").append(productInfoBuilder.toString()).append("\n");
            }

            // 出厂编号
            if (problem.getProductionNumber() != null && !problem.getProductionNumber().isEmpty()) {
                dateContent.append("出厂编号：").append(problem.getProductionNumber()).append("\n");
            }

            // 站点和位置 (安装站名 · 安装位置)
            StringBuilder locationInfoBuilder = new StringBuilder();
            if (problem.getInstallStation() != null && !problem.getInstallStation().isEmpty()) {
                locationInfoBuilder.append(problem.getInstallStation()).append("");
            }
            if (problem.getInstallationLocation() != null && !problem.getInstallationLocation().isEmpty()) {
                if (locationInfoBuilder.length() > 0) locationInfoBuilder.append(" · ");
                locationInfoBuilder.append("安装位置：").append(problem.getInstallationLocation());
            }
            if (locationInfoBuilder.length() > 0) {
                dateContent.append("安装站名：").append(locationInfoBuilder.toString()).append("\n");
            }

            // 安装日期
            if (problem.getInstallationDate() != null) {
                dateContent.append("安装日期：").append(problem.getInstallationDate()).append("\n");
            }

            // 故障现象
            if (problem.getFaultDescription() != null && !problem.getFaultDescription().isEmpty()) {
                dateContent.append("故障原因：").append(problem.getFaultDescription()).append("\n");
            }

            // 原因分析
            if (problem.getFaultAnalysis() != null && !problem.getFaultAnalysis().isEmpty()) {
                dateContent.append("原因分析：").append(problem.getFaultAnalysis()).append("\n");
            }

            // 处理结果/排除方法 (优先使用 resolutionResult，如果没有则用 resolutionMethod)
            String solution = problem.getResolutionResult();
            if (solution == null || solution.isEmpty()) {
                solution = problem.getResolutionMethod();
            }
            if (solution != null && !solution.isEmpty()) {
                dateContent.append("解决方案：").append(solution).append("\n");
            }

            // 改进意见
            if (problem.getImprovementSuggestions() != null && !problem.getImprovementSuggestions().isEmpty()) {
                dateContent.append("处理建议：").append(problem.getImprovementSuggestions()).append("\n");
            }

            // 备注
            if (problem.getRemark() != null && !problem.getRemark().isEmpty()) {
                dateContent.append("备注：").append(problem.getRemark()).append("\n");
            }



            // 创建人
//            if (problem.getCreatedBy() != null && !problem.getCreatedBy().isEmpty()) {
//                dateContent.append("创建人：").append(problem.getCreatedBy()).append("\n");
//            }

            // 添加一个空行，分隔不同问题
            dateContent.append("\n");

        }

        // 10. 构建最终返回的字符串
        StringBuilder finalResult = new StringBuilder();

        // 遍历按日期分组的结果
        for (java.util.Map.Entry<String, StringBuilder> entry : resultMap.entrySet()) {
            String dateStr = entry.getKey();
            String contentForDate = entry.getValue().toString();

            // 计算该日期下的问题条数
            long count = contentForDate.lines().filter(line -> line.startsWith("🔹 问题")).count();

            // 拼接日期标题和条数
            finalResult.append("📅 ").append(dateStr).append(" 问题汇总（共").append(count).append("条）\n\n");
            // 拼接该日期下的所有问题内容
            finalResult.append(contentForDate);
            // 在不同日期组之间添加分隔线 (可选)
            finalResult.append("——\n\n");
        }

        // 11. 移除末尾可能多余的分隔线和换行
        int lastSeparatorIndex = finalResult.lastIndexOf("——\n\n");
        if (lastSeparatorIndex != -1) {
            finalResult.delete(lastSeparatorIndex, finalResult.length());
        }

        // 12. 返回成功结果
        return ResponseResult.success(finalResult.toString());
    }

}
